/*
 * Copyright (C) 2008, 3apple team, All Rights Reserved
 * Author: James Cook <C.James.CJ@gmail.com>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */
#include "mod_priv.h"

list_head(apple_modules);

#define for_each_apple_modules(m)	\
	list_for_each_entry(apple_module_t, m, &apple_modules, link)

apple_module_t *apple_find_module(const char *name)
{
	list_t *n, *pos;
	apple_module_t *apple;

	list_iterate_forward(pos, n, &apple_modules) {
		apple = list_entry(pos, apple_module_t, link);
		if (strcasecmp(apple->name, name) == 0)
			return apple;
	}
	return NULL;
}

int register_apple_module(apple_module_t *apple)
{
	if (apple) {
		if (apple_find_module(apple->name)) {
			printf("MODULE: already registered module, module=%s",
				apple->name);
			return 0;
		}
		list_init(&apple->link);
		list_insert_before(&apple->link, &apple_modules);
	}
	return 0;
}

void unregister_apple_module(apple_module_t *apple)
{
	if (apple) {
		if (apple_find_module(apple->name))
			list_delete_init(&apple->link);
	}
}

int module_call_mods_init(void)
{
	apple_module_t *m;
	for_each_apple_modules(m) {
		if (m && m->init)
			m->init(m);
	}
	return 0;
}

void module_call_mods_exit(void)
{
	apple_module_t *m;
	for_each_apple_modules(m) {
		if (m && m->exit)
			m->exit();
	}
}

int module_call_mod_start(const char *name)
{
	apple_module_t *m = apple_find_module(name);
	if (m && m->start)
		return m->start(m);
	printf("module start fatal [%s]\n", name);
	return -1;

}

int apple_module_init(void)
{
	/* register */
	module_term_init();
	module_grah_init();
	/* module self init */
	module_call_mods_init();
	return 0;
}

void apple_module_exit(void)
{
	module_call_mods_exit();
	module_grah_exit();
	module_term_exit();
}

